import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { ElMessage } from "element-plus";
import {useCounterStore} from '../stores/counter'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',redirect:'/login',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/index',
      name: 'index',
      component: () => import('../views/Index.vue'),
      children:[
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('../views/HomeChild/Welcome.vue')
        },
      ],
      beforeEnter:(to,from,next,)=>{
          if(!localStorage.getItem('token')){
            ElMessage({
              showClose: true,
              message: '请先登录',
              type: "error",
            });
            next('/login')
          }else{
             next() 
          }
      }
    },
    {
      path: '/:catchAll(.*)',
      name: '404',
      component: () => import('../views/404.vue'),
  }
  ]
})
let flag = true
router.beforeEach((to,from,next)=>{
     if(localStorage.getItem('token')){
      const stores = useCounterStore()
        if(flag==true&&stores.allright.length != 0){
             stores.allright.forEach(item=>{
                 item.component = getComponent(item.name)           
                 router.addRoute("index",item)
                 console.log(router.getRoutes());
                 
             })
             flag = false
             next({
              ...to,
              replace:true
             })
        }else{

          next()
        }
          
     }else{
      if(to.path=='/login'){
          next()
      }else{
        ElMessage({
          showClose: true,
          message: '请先登录',
          type: "error",
        });
         next('/login')
      }
     }
})


function getComponent(name){
  console.log(name);
     return ()=>import(`../views/HomeChild/${name}.vue`)
}


export default router
